<template>
  <section v-loading="loading" class="cms-body">
    <div class="cms-list-header">
      <el-button type="primary"
                 icon="el-icon-plus"
                 @click="add"
                 v-perms="'/dictionary/add'"
      >添加</el-button>
      <!--这里放省市选择器-->
      <div class="l-dsp-ib">
      <area-select v-model="selected" :data="pca"></area-select>
      </div>
    </div>
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column prop="id" label="编码" width="150" align="center"></el-table-column>
      <el-table-column prop="name" label="名称" align="center"></el-table-column>
      <el-table-column  label="操作" align="center">
        <div slot-scope="scope">
          <cms-button type="edit" @click.native="edit(scope.row.name,scope.row.id)"
                      v-perms="'/dictionary/edit'"
          ></cms-button>
          <cms-button type="delete" @click.native="doDelete(scope.row.id)"
                      v-perms="'/dictionary/delete'"
          ></cms-button>
        </div>
      </el-table-column>
    </el-table>
    <el-dialog  title="地区 - 添加" :visible.sync="dialogVisible" width="27%" :before-close="handleClose">
                <span>
                     <el-form ref="form" label-width="80px" :model='addParam' :rules="rules">
                           <el-form-item label="所属">
                                <el-input v-model="belongs" class="cms-width" :disabled="true"></el-input>
                            </el-form-item>
                            <el-form-item label="编码" prop="id">
                                <el-input v-model="addParam.id" class="cms-width" :disabled="true"></el-input>
                                <!--<span v-show="updateCheck" class="red">所属分类已有此值</span>-->
                            </el-form-item>
                            <el-form-item label="区名" prop="name">
                                <el-input v-model="addParam.name" class="cms-width"></el-input>
                            </el-form-item>
                      </el-form>
                </span>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="save">确定</el-button>
                </span>
    </el-dialog>
    <el-dialog title="地区 - 修改" :visible.sync="dialogVisible1"  width="30%"  :close-on-click-modal="false"  :before-close = "handleClose" >
      <span>
        <el-form ref='form1' :model='updateParam' :rules="rules"  label-width="80px">
          <el-form-item label="所属">
              <el-input v-model="belongs" class="cms-width" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="编码" prop="id">
              <el-input v-model="updateParam.id" class="cms-width" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="区名"  prop="name">
              <el-input v-model="updateParam.name" class="cms-width"></el-input>
              <!--<span v-show="updateCheck" class="red">所属分类已有此值</span>-->
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取消</el-button>
        <el-button type="primary" @click="update">确定</el-button>
      </span>
    </el-dialog>
  </section>
</template>

<script>
  import Vue from 'vue';
  import {pca} from 'area-data'; // v5 or higher
  import 'vue-area-linkage/dist/index.css'; // v2 or higher
  import VueAreaLinkage from 'vue-area-linkage';
  Vue.use(VueAreaLinkage)
  //
  //
  //
  import va from "@/rules";
  import axios from "axios";
  export default {
    data() {
      let self = this;
      let required = va.required('此项必填');
      return {
        loading: false, //遮罩层
        tableData: [], //表格数据
        state: false,
        pca:pca,
        selected:[],
        parentKey: null,
        grandParentName:'',
        parentName:'',
        newKey:0,
        dialogVisible: false,
        dialogVisible1: false,
        tapTipSave:false,
        updateCheck:true,
        addCheck:false,
        addParam:{
          id:'',
          name:'',
          parent_key:'',
          level:3
        },
        updateParam:{
          id:'',
          name:''
        },
        rules: {//校验规则
          id:[required],
          name:[required],
        },
      };
    },
    computed:{
      belongs:function(){return this.grandParentName+' '+this.parentName;}
    },
    methods:{
      updateTableData(){
        axios.get(this.$api.areaLink).then(res => {
          localStorage.setItem('pcaa', JSON.stringify(res.body));
          let val = this.selected;
          let pcaa = JSON.parse(localStorage.getItem('pcaa'));
          let areaData = pcaa[val[1]];
          this.grandParentName = new RegExp('\\\\"'+val[0]+'\\\\":\\\\"([^\\\\]+)\\\\"').exec(JSON.stringify(localStorage.getItem('pcaa')))[1];
          this.parentKey = val[1];
          this.parentName = new RegExp('\\\\"'+val[1]+'\\\\":\\\\"([^\\\\]+)\\\\"').exec(JSON.stringify(localStorage.getItem('pcaa')))[1];
          if(!pcaa[this.selected[1]]){
            let tmp = pcaa[this.selected[0]];
            let new_key = Object.keys(tmp)[0];
            this.parentKey = new_key;
            this.parentName = new RegExp('\\\\"'+new_key+'\\\\":\\\\"([^\\\\]+)\\\\"').exec(JSON.stringify(localStorage.getItem('pcaa')))[1];
            areaData = pcaa[new_key];
          }
          this.tableData = [];
          this.newKey = Math.max(...Object.keys(areaData).map(function(val){
            return parseInt(val);
          }));
          Object.keys(areaData).forEach(key=>{
            this.tableData.push({'id': key, 'name': areaData[key], 'type':'1', 'value':'0'});
          });
        });
      },
      doDelete(id){
        this.$confirm('是否确定删除？', '警告', { type: "error" })
          .then(mes => {
            this.$http.post(this.$api.areaDelete, { id: id }).then(res => {
              if (res.code == "200") {
                this.successMessage('删除成功');
                this.updateTableData();
              }
            });
          })
          .catch(error => { });
      },
      add(){
        this.addParam.name='';
        this.addParam.id = this.newKey + 1;
        this.dialogVisible = true;
      },
      save(){
        let form = this.$refs['form'];
        form.validate((valid) => {//验证方法
          if(valid){
            this.$http
              .post(this.$api.areaSave,this.addParam)
              .then(res => {
                if(res.message==='成功!'){
                  this.dialogVisible=false;
                  // this.initTableData(this.$api.dictionaryList,this.params);
                  this.successMessage(res.message);
                  this.updateTableData();
                }
                this.loading = false;
              })
              .catch(error => {
                this.dialogVisible=false;
                this.loading = false;
              })
          }else{
            return false
          }
        })
      },
      edit(name,id){
        this.updateParam.name=name;
        this.updateParam.id=id;
        this.tapTipSave=false;
        this.updateCheck=false;
        this.dialogVisible1=true;

      },
      update(){
        let form = this.$refs['form1'];
        form.validate((valid) => {//验证方法
          if(valid){
            this.$http
              .post(this.$api.areaUpdate,this.updateParam)
              .then(res => {
                if(res.message==='成功!'){
                  this.dialogVisible1=false;
                  this.successMessage(res.message);
                  this.updateTableData();
                }
                this.loading = false;
              })
              .catch(error => {
                this.dialogVisible=false;
                this.loading = false;
              })
          }else{
            return false
          }
        })
      },
      handleClose(done) {
        done();
      }
    },
    created(){
      this.selected = ["110000", "110101"];
    },
    watch:{
      selected: function(val){
        let pcaa = JSON.parse(localStorage.getItem('pcaa'));
        let areaData = pcaa[val[1]];
        let areaDataString = JSON.stringify(localStorage.getItem('pcaa'));
        let matchReg = new RegExp('\\\\"'+val[0]+'\\\\":\\\\"([^\\\\]+)\\\\"');
        this.grandParentName = matchReg.exec(areaDataString)[1];
        this.parentKey = val[1];
        this.parentName = matchReg.exec(areaDataString)[1];
        if(!pcaa[this.selected[1]]){
          let tmp = pcaa[this.selected[0]];
          let new_key = Object.keys(tmp)[0];
          this.parentKey = new_key;
          this.parentName = matchReg.exec(areaDataString)[1];
          areaData = pcaa[new_key];
        }
        this.tableData = [];
        this.newKey = Math.max(...Object.keys(areaData).map(function(val){
           return parseInt(val);
        }));
        for(let key in areaData){
          this.tableData.push({'id': key, 'name': areaData[key], 'type':'1', 'value':'0'});
        }
        // Object.keys(areaData).forEach(key=>{
        //   this.tableData.push({'id': key, 'name': areaData[key], 'type':'1', 'value':'0'});
        // });
      },
      parentKey: function(val){
          this.addParam.parent_key = val;
          //console.log('parent_key:'+this.addParam.parent_key);
      }
    }
  };
</script>
<style scoped>
  .l-dsp-ib{
    display: inline-block;
    vertical-align: top;
  }
</style>
